using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Azure.Domain.Models;
using Azure.Domain.Services;
using Azure.Infrastructure;
using Azure.Web.Models;

namespace Azure.Web.Controllers
{
    public class FeedController : BaseController
    {
        private readonly IBlogService _blogService;

        public FeedController(IBlogService blogService, IBlogConfiguration configuration) : base(configuration)
        {
            _blogService = blogService;
        }

        [ActionName(Feed.Atom)]
        public ActionResult Atom()
        {
            var posts = _blogService.Last(20);
            var items = new List<SyndicationItem>();
            foreach (var post in posts)
            {
                var item = new SyndicationItem
                               {
                                   Title = new TextSyndicationContent(post.Title),
                                   Content = new BlogContent(post, Url.Link(post)),
                                   Id = post.RowKey,
                                   LastUpdatedTime = post.Timestamp,
                                   PublishDate = post.Created
                               };
                item.Authors.Add(new SyndicationPerson(String.Empty, post.Author, String.Empty));
                item.AddPermalink(Url.Link(post));
                items.Add(item);
            }

            var routeValues = new RouteValueDictionary();
            routeValues["action"] = Blog.Index;
            routeValues["controller"] = Blog.Controller;

            var feed = new SyndicationFeed(
                Configuration.Title, 
                Configuration.SubTitle,
                new Uri(Url.Link(Url.RouteUrl(routeValues))),
                items);
            return new AtomFeedResult(feed);
        }
    }

    public class BlogContent : TextSyndicationContent
    {
        private readonly Uri _link;

        public BlogContent(Post post, Uri link) : base(post.Body, TextSyndicationContentKind.Html)
        {
            _link = link;
        }

        protected override void WriteContentsTo(System.Xml.XmlWriter writer)
        {
            base.WriteContentsTo(writer);
            writer.WriteRaw(HttpUtility.HtmlEncode(String.Format("<p><a href=\"{0}\">View Post</a></p>", _link)));
        }
    }

    public static class Feed
    {
        public const string Controller = "Feed";
        public const string Atom = "Index";
    }
}